import utils from "./utils.js"

function Compiler(el, vm) {
  this.$el = this.isElementNode(el) ? el : document.querySelector(el)
  this.vm = vm
  const f = this.compileFragment(this.$el)
  // console.dir(this.$el)
  this.compile(f)
  this.$el.appendChild(f)
}

Compiler.prototype.compile = function (f) {
  console.dir(f)
  const childs = Array.from(f.childNodes)
  childs.forEach(child => {
    if (this.isElementNode(child)) {
      this.compileElement(child)
    } else if (this.isTextNode(child)) {
      this.compileText(child)
    }
    if (child.childNodes && child.childNodes.length > 0) {
      this.compile(child)
    }
  })
}

Compiler.prototype.compileElement = function (node) {
  const attributes = Array.from(node.attributes)
  // console.log(attributes)
  attributes.forEach(attr => {
    const { name, value } = attr
    console.log(name, value)
    if (this.isDirector(name)) {
      // 指令 v-model v-on:click v-text v-bind
      const [,director] = name.split('-')
      const [directorName, eventName ] = director.split(':')
      utils[directorName](node, value, this.vm, eventName)
    } else if (this.isEventor(name)) {
      const eventName = name.split('@')[1]
      utils['on'](node, value, this.vm, eventName)
    }
  })
}

Compiler.prototype.compileText = function (node) {
  const content = node.textContent
  if (/\{\{(.+)\}\}/.test(content)) {
    console.log('content=== ',content)
    utils['text'](node, content, this.vm)
  }
}

Compiler.prototype.compileFragment = function (el) {
  let f = document.createDocumentFragment()
  let firstChild
  while (firstChild = el.firstChild) {
    f.appendChild(el.firstChild)
  }
  return f
}
Compiler.prototype.isDirector = function (attr) {
  console.log(attr)
  return attr.startsWith('v-')
}
Compiler.prototype.isEventor = function (attr) {
  return attr.startsWith('@')
}
Compiler.prototype.isElementNode = function (el) {
  return el.nodeType === 1
}
Compiler.prototype.isTextNode = function (el) {
  return el.nodeType === 3
}

export default Compiler